import os
import json

# 指定数据目录和输出目录
GACHA_DATA_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_Gacha.json'
PCTABLE_DATA_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_PCTable.json'
PET_DATA_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_Pet.json'
CURRENCY_ETC_DATA_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_CurrencyETC.json'
COLLECTION_BOOK_GROUP_LIST_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_CollectionBookGroupList.json'
COLLECTION_BOOK_CATEGORY_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_CollectionBookCategory.json'
GUIDE_QUEST_MISSION_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_GuideQuestMission.json'
INDIVIDUAL_MISSION_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_IndividualMission.json'
PC_REINFORCEMENT_COST_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_PCReinforcementCost.json'
STAGE_ACHIEVEMENT_REWARD_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_StageAchievementReward.json'
PC_EVOLUTION_MATERIAL_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_PCEvolutionMaterial.json'
CONVERSION_DATA_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_Conversion.json'
CONVERSION_RECIPE_DATA_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\GameData\DT_ConversionRecipe.json'
CN_LANG_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\StringTable\zh-Hans\String_PCTable.json'
ZH_LANG_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\StringTable\zh-Hant\String_PCTable.json'
UI_LANG_FILE = r'G:\工作区\项目\UE引擎\2.七骑士\资源数据\StringTable\zh-Hans\String_UITable.json'
OUTPUT_DIR = os.path.join('Res', 'Dbc')
os.makedirs(OUTPUT_DIR, exist_ok=True)

def read_json_data(file_path):
    """读取JSON文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print(f'文件未找到: {file_path}')
        return None
    except json.JSONDecodeError as e:
        print(f'JSON解析错误: {e}')
        return None
    except Exception as e:
        print(f'读取文件时发生错误: {e}')
        return None

def read_language_table(file_path):
    """读取语言表文件，按行解析Key,SourceString格式"""
    lang_dict = {}
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                line = line.strip()
                if line and ',' in line:
                    # 解析格式: "Key","SourceString"
                    parts = line.split(',', 1)
                    if len(parts) == 2:
                        key = parts[0].strip('"')
                        value = parts[1].strip('"')
                        lang_dict[key] = value
        return lang_dict
    except FileNotFoundError:
        print(f'语言表文件未找到: {file_path}')
        return {}
    except Exception as e:
        print(f'读取语言表文件时发生错误: {e}')
        return {}



def process_gacha_data():
    """处理Gacha数据并输出到gacha.json"""
    print('正在读取DT_Gacha.json...')
    gacha_data = read_json_data(GACHA_DATA_FILE)
    
    if not gacha_data:
        print('DT_Gacha.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in gacha_data[0]:
        print('DT_Gacha.json中未找到Rows字段')
        return
    
    rows_data = gacha_data[0]['Rows']
    gacha_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        # 提取指定字段
        gacha_item = {
            'TID': row_data.get('TID', ''),
            'GachaType': row_data.get('GachaType', 0),
            'Order': row_data.get('Order', 0),
            'MainPCTID': row_data.get('MainPCTID', ''),
            'GachaCeilingTID': row_data.get('GachaCeilingTID', ''),
            'PreviousGachaTID': row_data.get('PreviousGachaTID', ''),
            'DrawLimit': row_data.get('DrawLimit', 0),
            'CurrencyID': row_data.get('CurrencyID', 0),
            'Ruby': row_data.get('Ruby', 0)
        }
        gacha_list.append(gacha_item)
    
    # 按Order字段排序
    gacha_list.sort(key=lambda x: x['Order'])
    
    # 输出到gacha.json文件
    output_file = os.path.join(OUTPUT_DIR, 'gacha.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(gacha_list, f, ensure_ascii=False, indent=2)
        print(f'gacha.json处理完成！共处理了{len(gacha_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_pet_data():
    """处理Pet数据并输出到pet.json"""
    print('正在读取DT_Pet.json...')
    pet_data = read_json_data(PET_DATA_FILE)
    
    if not pet_data:
        print('DT_Pet.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in pet_data[0]:
        print('DT_Pet.json中未找到Rows字段')
        return
    
    # 读取语言表
    print('正在读取韩文语言表...')
    cn_lang_dict = read_language_table(CN_LANG_FILE)
    print('正在读取中文语言表...')
    zh_lang_dict = read_language_table(ZH_LANG_FILE)
    
    rows_data = pet_data[0]['Rows']
    pet_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        name_text_id = row_data.get('NameTextID', '')
        name_text_id_arr = name_text_id.split('.')
        # 从语言表中获取名称
        name_cn = cn_lang_dict.get(name_text_id_arr[len(name_text_id_arr)-1], '')
        name = zh_lang_dict.get(name_text_id_arr[len(name_text_id_arr)-1], '')
        
        sub_name_text_id = row_data.get('SubNameTextID', '')
        sub_name_text_id_arr = sub_name_text_id.split('.')
        # 从语言表中获取副名称
        sub_name_cn = cn_lang_dict.get(sub_name_text_id_arr[len(sub_name_text_id_arr)-1], '')
        sub_name = zh_lang_dict.get(sub_name_text_id_arr[len(sub_name_text_id_arr)-1], '')
        
        # 提取指定字段
        pet_item = {
            'TID': row_data.get('TID', ''),
            'GroupID': row_data.get('GroupID', ''),
            'Rarity': row_data.get('Rarity', 0),
            'NameTextID': name_text_id,
            'SubNameTextID': sub_name_text_id,
            'Star': row_data.get('Star', 0),
            'OriginStar': row_data.get('OriginStar', 0),
            'MaxStar': row_data.get('MaxStar', 0),
            'PetStatTID': row_data.get('PetStatTID', ''),
            'Special': row_data.get('Special', 0),
            'name_cn': name_cn,
            'name': name,
            'sub_name_cn': sub_name_cn,
            'sub_name': sub_name
        }
        pet_list.append(pet_item)
    
    # 按TID字段排序
    pet_list.sort(key=lambda x: x['TID'])
    
    # 输出到pet.json文件
    output_file = os.path.join(OUTPUT_DIR, 'pet.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(pet_list, f, ensure_ascii=False, indent=2)
        print(f'pet.json处理完成！共处理了{len(pet_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_pctable_data():
    """处理PCTable数据并输出到pctable.json"""
    print('正在读取DT_PCTable.json...')
    pctable_data = read_json_data(PCTABLE_DATA_FILE)
    
    if not pctable_data:
        print('DT_PCTable.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in pctable_data[0]:
        print('DT_PCTable.json中未找到Rows字段')
        return
    
    # 读取语言表
    print('正在读取韩文语言表...')
    cn_lang_dict = read_language_table(CN_LANG_FILE)
    print('正在读取中文语言表...')
    zh_lang_dict = read_language_table(ZH_LANG_FILE)
    
    rows_data = pctable_data[0]['Rows']
    pctable_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        name_text_id = row_data.get('NameTextID', '')
        name_text_id_arr = name_text_id.split('.')
        # 从语言表中获取名称
        name_cn = cn_lang_dict.get(name_text_id_arr[len(name_text_id_arr)-1], '')
        name = zh_lang_dict.get(name_text_id_arr[len(name_text_id_arr)-1], '')
        subname_text_id = row_data.get('SubNameTextID', '')
        subname_text_id_arr = subname_text_id.split('.')
        # 从语言表中获取名称
        subname_cn = cn_lang_dict.get(subname_text_id_arr[len(subname_text_id_arr) - 1], '')
        subname = zh_lang_dict.get(subname_text_id_arr[len(subname_text_id_arr) - 1], '')
        # 提取指定字段
        pctable_item = {
            'TID': row_data.get('TID', ''),
            'GroupTID': row_data.get('GroupTID', ''),
            'Playable': row_data.get('Playable', False),
            'NameTextID': name_text_id,
            'Role': row_data.get('Role', 0),
            'Star': row_data.get('Star', 0),
            'OriginStar': row_data.get('OriginStar', 0),
            'Rarity': row_data.get('Rarity', 0),
            'Range': row_data.get('Range', 0),
            'StatID': row_data.get('StatID', ''),
            'RecommendedEquipGroup': row_data.get('RecommendedEquipGroup', 0),
            'MaxStar': row_data.get('MaxStar', 0),
            'Special': row_data.get('Special', 0),
            'WeaponType': row_data.get('WeaponType', 0),
            'Statistics': row_data.get('Statistics', {}),
            'name_cn': name_cn,
            'name': name,
            'subname_cn':subname_cn,
            'subname':subname
        }
        pctable_list.append(pctable_item)
    
    # 按TID字段排序
    pctable_list.sort(key=lambda x: x['TID'])
    
    # 输出到pctable.json文件
    output_file = os.path.join(OUTPUT_DIR, 'pctable.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(pctable_list, f, ensure_ascii=False, indent=2)
        print(f'pctable.json处理完成！共处理了{len(pctable_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_currency_etc_data():
    """处理CurrencyETC数据并输出到currency_etc.json"""
    print('正在读取DT_CurrencyETC.json...')
    currency_etc_data = read_json_data(CURRENCY_ETC_DATA_FILE)
    
    if not currency_etc_data:
        print('DT_CurrencyETC.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in currency_etc_data[0]:
        print('DT_CurrencyETC.json中未找到Rows字段')
        return
    
    # 读取UI语言表
    print('正在读取UI语言表...')

    ui_lang_dict = read_language_table(UI_LANG_FILE)
    rows_data = currency_etc_data[0]['Rows']
    currency_etc_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        currency_name_id = row_data.get('CurrencyNameID', '')
        
        # 将CurrencyNameID按'.'分割，取最后一部分
        name_key = ''
        name = ''
        if currency_name_id:
            name_parts = currency_name_id.split('.')
            if len(name_parts) > 0:
                name_key = name_parts[-1]  # 取最后一部分
                # 从UI语言表中获取名称
                if name_key in ui_lang_dict:
                    ui_item = ui_lang_dict[name_key]
                    # UI语言表的结构可能是对象，需要获取SourceString字段
                    if isinstance(ui_item, dict) and 'SourceString' in ui_item:
                        name = ui_item['SourceString']
                    elif isinstance(ui_item, str):
                        name = ui_item
        
        # 提取指定字段
        currency_etc_item = {
            'CurrencyID': row_data.get('CurrencyID', 0),
            'CurrencyNameID': currency_name_id,
            'name': name
        }
        currency_etc_list.append(currency_etc_item)
    
    # 按CurrencyID字段排序
    currency_etc_list.sort(key=lambda x: x['CurrencyID'])
    
    # 输出到currency_etc.json文件
    output_file = os.path.join(OUTPUT_DIR, 'currency_etc.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(currency_etc_list, f, ensure_ascii=False, indent=2)
        print(f'currency_etc.json处理完成！共处理了{len(currency_etc_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_collection_book_data():
    """处理CollectionBook数据并输出到collection_book.json"""
    print('正在读取DT_CollectionBookGroupList.json...')
    collection_book_group_data = read_json_data(COLLECTION_BOOK_GROUP_LIST_FILE)
    
    if not collection_book_group_data:
        print('DT_CollectionBookGroupList.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in collection_book_group_data[0]:
        print('DT_CollectionBookGroupList.json中未找到Rows字段')
        return
    
    print('正在读取DT_CollectionBookCategory.json...')
    collection_book_category_data = read_json_data(COLLECTION_BOOK_CATEGORY_FILE)
    
    if not collection_book_category_data:
        print('DT_CollectionBookCategory.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in collection_book_category_data[0]:
        print('DT_CollectionBookCategory.json中未找到Rows字段')
        return
    
    # 建立CollectionBookCategory的TID到BookType和StoryBookType的映射
    category_mapping = {}
    category_rows_data = collection_book_category_data[0]['Rows']
    for row_key, row_data in category_rows_data.items():
        tid = row_data.get('TID', '')
        book_type = row_data.get('BookType', 0)
        story_book_type = row_data.get('StoryBookType', 0)
        category_mapping[tid] = {
            'BookType': book_type,
            'StoryBookType': story_book_type
        }
    
    rows_data = collection_book_group_data[0]['Rows']
    collection_book_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        collection_book_category_tid = row_data.get('CollectionBookCategoryTID', '')
        
        # 从category_mapping中获取BookType和StoryBookType
        book_type = 0
        story_book_type = 0
        if collection_book_category_tid in category_mapping:
            book_type = category_mapping[collection_book_category_tid]['BookType']
            story_book_type = category_mapping[collection_book_category_tid]['StoryBookType']
        
        # 提取指定字段
        collection_book_item = {
            'CollectionBookCategoryTID': collection_book_category_tid,
            'GroupTID': row_data.get('GroupTID', ''),
            'Reward': row_data.get('Reward', {}),
            'BookType': book_type,
            'StoryBookType': story_book_type
        }
        collection_book_list.append(collection_book_item)
    
    # 按GroupTID字段排序
    collection_book_list.sort(key=lambda x: x['GroupTID'])
    
    # 输出到collection_book.json文件
    output_file = os.path.join(OUTPUT_DIR, 'collection_book.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(collection_book_list, f, ensure_ascii=False, indent=2)
        print(f'collection_book.json处理完成！共处理了{len(collection_book_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_guide_quest_mission_data():
    """处理GuideQuestMission数据并输出到guide_quest_mission.json"""
    print('正在读取DT_GuideQuestMission.json...')
    guide_quest_mission_data = read_json_data(GUIDE_QUEST_MISSION_FILE)
    
    if not guide_quest_mission_data:
        print('DT_GuideQuestMission.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in guide_quest_mission_data[0]:
        print('DT_GuideQuestMission.json中未找到Rows字段')
        return
    
    rows_data = guide_quest_mission_data[0]['Rows']
    guide_quest_mission_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        # 提取指定字段
        guide_quest_mission_item = {
            'TID': row_data.get('TID', ''),
            'EventMainTID': row_data.get('EventMainTID', ''),
            'MissionType': row_data.get('MissionType', 0),
            'Count': row_data.get('Count', 0),
            'Page': row_data.get('Page', 0),
            'GuideQuestOrder': row_data.get('GuideQuestOrder', 0)
        }
        guide_quest_mission_list.append(guide_quest_mission_item)
    
    # 按TID字段排序
    guide_quest_mission_list.sort(key=lambda x: x['TID'])
    
    # 输出到guide_quest_mission.json文件
    output_file = os.path.join(OUTPUT_DIR, 'guide_quest_mission.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(guide_quest_mission_list, f, ensure_ascii=False, indent=2)
        print(f'guide_quest_mission.json处理完成！共处理了{len(guide_quest_mission_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_individual_mission_data():
    """处理IndividualMission数据并输出到individual_mission.json"""
    print('正在读取DT_IndividualMission.json...')
    individual_mission_data = read_json_data(INDIVIDUAL_MISSION_FILE)
    
    if not individual_mission_data:
        print('DT_IndividualMission.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in individual_mission_data[0]:
        print('DT_IndividualMission.json中未找到Rows字段')
        return
    
    rows_data = individual_mission_data[0]['Rows']
    individual_mission_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        # 提取指定字段
        individual_mission_item = {
            'MissionID': row_data.get('MissionID', 0),
            'RepeatType': row_data.get('RepeatType', 0),
            'PeriodType': row_data.get('PeriodType', 0),
            'IsRepeat': row_data.get('IsRepeat', 0),
            'RepeatGroup': row_data.get('RepeatGroup', 0),
            'MissionType': row_data.get('MissionType', 0),
            'Count': row_data.get('Count', 0),
            'IndividualMissionPoint': row_data.get('IndividualMissionPoint', 0)
        }
        individual_mission_list.append(individual_mission_item)
    
    # 按MissionID字段排序
    individual_mission_list.sort(key=lambda x: x['MissionID'])
    
    # 输出到individual_mission.json文件
    output_file = os.path.join(OUTPUT_DIR, 'individual_mission.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(individual_mission_list, f, ensure_ascii=False, indent=2)
        print(f'individual_mission.json处理完成！共处理了{len(individual_mission_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_pc_reinforcement_cost_data():
    """处理PCReinforcementCost数据并输出到pc_reinforcement_cost.json"""
    print('正在读取DT_PCReinforcementCost.json...')
    pc_reinforcement_cost_data = read_json_data(PC_REINFORCEMENT_COST_FILE)
    
    if not pc_reinforcement_cost_data:
        print('DT_PCReinforcementCost.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in pc_reinforcement_cost_data[0]:
        print('DT_PCReinforcementCost.json中未找到Rows字段')
        return
    
    rows_data = pc_reinforcement_cost_data[0]['Rows']
    pc_reinforcement_cost_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        # 提取指定字段
        pc_reinforcement_cost_item = {
            'PCStar': row_data.get('PCStar', 0),
            'PCReinforcementLevel': row_data.get('PCReinforcementLevel', 0),
            'PCReinforcementCost': row_data.get('PCReinforcementCost', 0)
        }
        pc_reinforcement_cost_list.append(pc_reinforcement_cost_item)
    
    # 按PCStar和PCReinforcementLevel字段排序
    pc_reinforcement_cost_list.sort(key=lambda x: (x['PCStar'], x['PCReinforcementLevel']))
    
    # 输出到pc_reinforcement_cost.json文件
    output_file = os.path.join(OUTPUT_DIR, 'pc_reinforcement_cost.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(pc_reinforcement_cost_list, f, ensure_ascii=False, indent=2)
        print(f'pc_reinforcement_cost.json处理完成！共处理了{len(pc_reinforcement_cost_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_stage_achievement_reward_data():
    """处理StageAchievementReward数据并输出到stage_achievement_reward.json"""
    print('正在读取DT_StageAchievementReward.json...')
    stage_achievement_reward_data = read_json_data(STAGE_ACHIEVEMENT_REWARD_FILE)
    
    if not stage_achievement_reward_data:
        print('DT_StageAchievementReward.json读取失败')
        return
    
    # 检查是否存在Rows字段
    if 'Rows' not in stage_achievement_reward_data[0]:
        print('DT_StageAchievementReward.json中未找到Rows字段')
        return
    
    rows_data = stage_achievement_reward_data[0]['Rows']
    stage_achievement_reward_list = []
    
    # 处理每一行数据
    for row_key, row_data in rows_data.items():
        # 提取所有相关字段
        stage_achievement_reward_item = {}
        for field_key, field_value in row_data.items():
            stage_achievement_reward_item[field_key] = field_value
        
        stage_achievement_reward_list.append(stage_achievement_reward_item)
    
    # 按TID字段排序（如果存在）
    if stage_achievement_reward_list and 'TID' in stage_achievement_reward_list[0]:
        stage_achievement_reward_list.sort(key=lambda x: x.get('TID', ''))
    
    # 输出到stage_achievement_reward.json文件
    output_file = os.path.join(OUTPUT_DIR, 'stage_achievement_reward.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(stage_achievement_reward_list, f, ensure_ascii=False, indent=2)
        print(f'stage_achievement_reward.json处理完成！共处理了{len(stage_achievement_reward_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_pc_evolution_material_data():
    """处理PCEvolutionMaterial数据并输出到pc_evolution_material.json"""
    print('正在读取DT_PCEvolutionMaterial.json...')
    pc_evolution_material_data = read_json_data(PC_EVOLUTION_MATERIAL_FILE)

    if not pc_evolution_material_data:
        print('DT_PCEvolutionMaterial.json读取失败')
        return

    if 'Rows' not in pc_evolution_material_data[0]:
        print('DT_PCEvolutionMaterial.json中未找到Rows字段')
        return

    rows_data = pc_evolution_material_data[0]['Rows']
    pc_evolution_material_list = []

    for row_key, row_data in rows_data.items():
        # 提取指定字段，排除 UniqueID
        pc_evolution_material_item = {
            'Star': row_data.get('Star', 0),
            'Role': row_data.get('Role', 0),
            'MaterialID': row_data.get('MaterialID', 0),
            'Count': row_data.get('Count', 0),
            'CostGold': row_data.get('CostGold', 0)
        }
        pc_evolution_material_list.append(pc_evolution_material_item)

    # 按Star和Role字段排序
    pc_evolution_material_list.sort(key=lambda x: (x['Star'], x['Role']))

    output_file = os.path.join(OUTPUT_DIR, 'pc_evolution_material.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(pc_evolution_material_list, f, ensure_ascii=False, indent=2)
        print(f'pc_evolution_material.json处理完成！共处理了{len(pc_evolution_material_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_conversion_data():
    """处理Conversion数据并输出到conversion.json"""
    print('正在读取DT_Conversion.json...')
    conversion_data = read_json_data(CONVERSION_DATA_FILE)

    if not conversion_data:
        print('DT_Conversion.json读取失败')
        return

    if 'Rows' not in conversion_data[0]:
        print('DT_Conversion.json中未找到Rows字段')
        return

    rows_data = conversion_data[0]['Rows']
    conversion_list = []

    for row_key, row_data in rows_data.items():
        # 提取所有字段
        conversion_list.append(row_data)

    # 尝试按TID字段排序，如果不存在则不排序
    if conversion_list and 'TID' in conversion_list[0]:
        conversion_list.sort(key=lambda x: x['TID'])
    elif conversion_list:
        # 如果没有TID，则按第一个键排序
        conversion_list.sort(key=lambda x: list(x.keys())[0])

    output_file = os.path.join(OUTPUT_DIR, 'conversion.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(conversion_list, f, ensure_ascii=False, indent=2)
        print(f'conversion.json处理完成！共处理了{len(conversion_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')

def process_conversion_recipe_data():
    """处理ConversionRecipe数据并与Conversion数据匹配后输出到conversion.json"""
    print('正在读取DT_Conversion.json...')
    conversion_data = read_json_data(CONVERSION_DATA_FILE)

    if not conversion_data:
        print('DT_Conversion.json读取失败')
        return

    if 'Rows' not in conversion_data[0]:
        print('DT_Conversion.json中未找到Rows字段')
        return

    conversion_lookup = {item['TID']: item for item in conversion_data[0]['Rows'].values() if 'TID' in item}

    print('正在读取DT_ConversionRecipe.json...')
    conversion_recipe_data = read_json_data(CONVERSION_RECIPE_DATA_FILE)

    if not conversion_recipe_data:
        print('DT_ConversionRecipe.json读取失败')
        return

    if 'Rows' not in conversion_recipe_data[0]:
        print('DT_ConversionRecipe.json中未找到Rows字段')
        return

    conversion_recipe_rows = conversion_recipe_data[0]['Rows']

    # 创建一个字典来存储每个ConversionTID对应的MaterialID和MaterialCount列表
    recipe_materials = {}
    for row_key, row_data in conversion_recipe_rows.items():
        conversion_tid = row_data.get('ConversionTID')
        if conversion_tid:
            if conversion_tid not in recipe_materials:
                recipe_materials[conversion_tid] = []
            recipe_materials[conversion_tid].append({
                'MaterialID': row_data.get('MaterialID', 0),
                'MaterialCount': row_data.get('MaterialCount', 0)
            })

    # 将MaterialID和MaterialCount合并到conversion_data中
    processed_conversion_list = []
    for tid, conversion_item in conversion_lookup.items():
        if tid in recipe_materials and recipe_materials[tid]:
            # 取第一个材料的MaterialID和MaterialCount
            first_material = recipe_materials[tid][0]
            conversion_item['MaterialID'] = first_material.get('MaterialID', 0)
            conversion_item['MaterialCount'] = first_material.get('MaterialCount', 0)
        else:
            conversion_item['MaterialID'] = 0
            conversion_item['MaterialCount'] = 0
        processed_conversion_list.append(conversion_item)

    # 尝试按TID字段排序
    if processed_conversion_list and 'TID' in processed_conversion_list[0]:
        processed_conversion_list.sort(key=lambda x: x['TID'])

    output_file = os.path.join(OUTPUT_DIR, 'conversion.json')
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(processed_conversion_list, f, ensure_ascii=False, indent=2)
        print(f'conversion.json处理完成！共处理了{len(processed_conversion_list)}条记录')
        print(f'输出文件: {output_file}')
    except Exception as e:
        print(f'写入文件时发生错误: {e}')


if __name__ == '__main__':
    # process_gacha_data()
    # process_pet_data()
    # process_pctable_data()
    # process_currency_etc_data()
    # process_collection_book_data()
    # process_guide_quest_mission_data()
    # process_individual_mission_data()
    # process_pc_reinforcement_cost_data()
    # process_stage_achievement_reward_data()
    # process_pc_evolution_material_data()
    process_conversion_recipe_data()